package sy.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import sy.dao.SysAccountAppFunctionMappingDaoI;
import sy.model.AppEquipment;
import sy.model.AppFunction;
import sy.model.SysAccountAppFunctionMapping;
@Repository("sysAccountAppFunctionMappingDao")
public class SysAccountAppFunctionMappingDaoImpl implements SysAccountAppFunctionMappingDaoI{
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session getCurrentSession(){
		return this.getSessionFactory().getCurrentSession();
	}

	@Override
	public Serializable deleteBySysAccountId(String sysAccountId) {
		// TODO Auto-generated method stub
		String hql = "delete from SysAccountAppFunctionMapping where sysAccountId = :sysAccountId";
		Query query = this.getCurrentSession().createQuery(hql);
		query.setString("sysAccountId", sysAccountId);
		return query.executeUpdate();
	}

	@Override
	public void saveBatch(List<SysAccountAppFunctionMapping> list) {
		// TODO Auto-generated method stub
		Session session = this.getCurrentSession();
		SysAccountAppFunctionMapping obj = null;
		for(int i = 0; i<list.size(); i++) {
			obj = list.get(i);
			session.save(obj);
			if (i % 10 == 0) {  
				session.flush();  
				session.clear();  
			} 
		}
	}
	@Override
	public List<AppFunction> listAppFunction(String accountId) {
		// TODO Auto-generated method stub
		String sql = "select b.id id,b.code code,b.name name,b.url url,b.iconUrl iconUrl,b.type from sys_account_app_function_mapping a left join "+
		    "app_function b on a.appFunctionId = b.id where sysAccountId  = :accountId";
		SQLQuery query = this.getCurrentSession().createSQLQuery(sql);
		query.setString("accountId", accountId);
		query.addScalar("id")
	    .addScalar("code")
	    .addScalar("name")
	    .addScalar("url")
	    .addScalar("iconUrl")
	    .addScalar("type")
	    .setResultTransformer(Transformers.aliasToBean(AppFunction.class));
		return query.list();
	}





}
